package com.songshuai.sales.tool.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.songshuai.sales.tool.dao.tool.SopManageMapper;
import com.songshuai.sales.tool.dao.tool.SopMapper;
import com.songshuai.sales.tool.dao.tool.SopTypeMapper;
import com.songshuai.sales.tool.dto.request.sopmanage.CustomerPushReqDto;
import com.songshuai.sales.tool.dto.request.sopmanage.CustomerQueryReqDto;
import com.songshuai.sales.tool.dto.request.sopmanage.DynamicQueryReqDto;
import com.songshuai.sales.tool.dto.request.sopmanage.SopManageListReqDto;
import com.songshuai.sales.tool.dto.response.login.LoginUserResDto;
import com.songshuai.sales.tool.dto.response.sopmanage.*;
import com.songshuai.sales.tool.model.SopType;
import com.songshuai.sales.tool.service.SopManageService;
import com.songshuai.sales.tool.util.PageUtil;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.model.sales.Sop;
import com.songshuai.webapi.baseapi.pojo.BaseParmDto;
import com.songshuai.webapi.baseapi.utils.SnowFlakeUtil;
import com.songshuai.webapi.common.httpclient.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Slf4j
@Service
public class SopManageServiceImpl extends BaseServiceImpl implements SopManageService{

    @Autowired
    private SnowFlakeUtil snowFlakeUtil;

    @Autowired
    private SopManageMapper sopManageMapper;

    @Autowired
    private SopTypeMapper sopTypeMapper;

    @Autowired
    private SopMapper sopMapper;

    @Value("${pangu.tool.addClueSopRecord}")
    private String addClueSopRecordUrl;


    @Override
    public PageUtil selectByMsg(BaseParmDto<CustomerQueryReqDto> request) {

        int count = 0;
        try {
            count = sopManageMapper.selectCount(request.getParam());
        } catch (Exception e) {
            throw new BusinessException(ResultStatus.ERROR_COUNT_FAILED);
        }
        //设置分页
        PageUtil page = new PageUtil(request.getPageIndex(), request.getPageSize(), count);
        request.getParam().setStart(page.getStart());
        request.getParam().setEnd(page.getEnd());
        List<CustomerActResDto> list = null;
        try {
            list = sopManageMapper.selectByMsg(request.getParam());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED);
        }
        page.setLists(list);
        return page;
    }

    @Override
    public List<SopActResDto> selectByActionUser(String actionUser) {
        List<SopActResDto> lists = null;
        try {
            lists = sopManageMapper.selectByActionUser(actionUser);
        } catch (Exception e) {
            throw new BusinessException(ResultStatus.ERROR_RECORD_NOT_FOUND);
        }
        return lists;
    }

    @Override
    public SopPreviewResDto showSopPreView(String sopId) {
        SopPreviewResDto sopPreviewResDto =null;
        try {
            sopPreviewResDto = sopManageMapper.showSopPreView(sopId);
        } catch (Exception e) {
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED);
        }
        return sopPreviewResDto;
    }

    @Override
    public Map queryBindStatus(String customerIds) {
        Map map = new HashMap();
        if(StringUtils.hasText(customerIds)){
            for(String customerId : customerIds.split(",")){
                Integer bindStatus = 0;
                Integer num = sopManageMapper.queryBindStatus(customerId);
                if(num > 0){
                    bindStatus = 1;
                }
                map.put(customerId, bindStatus);
            }
        }
        return map;
    }

    @Override
    public List<SopPushRecordResDto> selectSopPushRecord(String reciveUser) {
        List<SopPushRecordResDto> lists = null;
        try {
            lists = sopManageMapper.selectSopPushRecord(reciveUser);
        } catch (Exception e) {
            throw new BusinessException(ResultStatus.ERROR_RECORD_NOT_FOUND);
        }
        return lists;
    }

    @Override
    public PageUtil dynamicQuery(BaseParmDto<DynamicQueryReqDto> request) {//动态查询推送记录

        try {
            Integer count = sopManageMapper.selectPushRecordMapperCount(request.getParam());//获取分页数据

            PageUtil pageUtil = new PageUtil(request.getPageIndex(), request.getPageSize(), count);

            request.getParam().setStart(pageUtil.getStart());

            request.getParam().setEnd(pageUtil.getEnd());

            List<DynamicQueryResDto> list = sopManageMapper.dynamicQuery(request.getParam());

            pageUtil.setLists(list);
            return pageUtil;
        } catch (Exception exception) {
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }
    }


    @Override
    public PageUtil selectSopManageList(BaseParmDto<SopManageListReqDto> request) {//sop管理界面展示、查询

        LoginUserResDto loginUserResDto = this.getCurrentUser();//获取登陆信息
        if (null == loginUserResDto) {

            throw new BusinessException(ResultStatus.NO_LOGIN.getErrorMsg(), ResultStatus.FAILOfficial);
        }
        try {
            List<String> sopGroup = new ArrayList<>();
            if(CollectionUtils.isEmpty(request.getParam().getSopGroup())){
                String mainRole = loginUserResDto.getMainRole();
                String minorRole = loginUserResDto.getMinorRole();
                if(StringUtils.hasText(mainRole)){
                    sopGroup.add(mainRole);
                }
                if(StringUtils.hasText(minorRole)){
                    String[] minorRoles = minorRole.split(",");
                    for(String role : minorRoles){
                        sopGroup.add(role);
                    }
                }
                request.getParam().setSopGroup(sopGroup);
            }

            Integer count = sopManageMapper.selectSopManageListCount(request.getParam());

            PageUtil pageUtil = new PageUtil(request.getPageIndex(), request.getPageSize(), count);
            if(count > 0){
                request.getParam().setStart(pageUtil.getStart());
                request.getParam().setEnd(pageUtil.getEnd());
                List<SopManageListResDto> listResDtos = sopManageMapper.selectSopManageList(request.getParam());
                if (!CollectionUtils.isEmpty(listResDtos)) {
                    for (SopManageListResDto resDto : listResDtos) {
                        SopType mainTypeName = sopTypeMapper.selectByPrimaryKey(resDto.getMainType());
                        SopType subTypeName = sopTypeMapper.selectByPrimaryKey(resDto.getSubType());
                        if(mainTypeName != null){
                            resDto.setMainType(mainTypeName.getTypeName());
                        }
                        if(subTypeName != null){
                            resDto.setSubType(subTypeName.getTypeName());
                        }
                    }
                    pageUtil.setLists(listResDtos);
                }
            }
            return pageUtil;
        } catch (Exception e) {
            log.error("查询sop管理列表异常：{}", e);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }
    }

    @Override
    public SuccessResDto insertPushRecord(List<CustomerPushReqDto> list, String authorization) {
        SuccessResDto successResDto = new SuccessResDto();
        LoginUserResDto loginUserResDto = this.getCurrentUser();
        if (null == loginUserResDto) {
            throw new BusinessException(ResultStatus.NO_LOGIN.getErrorMsg(), ResultStatus.FAILOfficial);
        }
        String userId = loginUserResDto.getUserId();
        String userName = loginUserResDto.getTrueName();
        JSONObject json = new JSONObject();
        JSONArray sops = new JSONArray();
        Set<String> clueGuids = new HashSet<>();
        Map<String, Integer> failMap = new HashMap<String, Integer>();
        Map<String, Integer> successMap = new HashMap<String, Integer>();
        Set<String> sopIds = new HashSet<>();

        for(CustomerPushReqDto pushReqDto : list){
            String receiveUser = pushReqDto.getReciveUser();
            try {
                Integer isBind = sopManageMapper.queryBindStatus(receiveUser);
                if(isBind > 0){
                    // 插入到本地数据库前判断是否有推送过
                    Integer num = sopManageMapper.querySopPushCustomerStatus(pushReqDto.getSopId(), receiveUser);
                    if(num <= 0){
                        String sopId = pushReqDto.getSopId();
                        Sop querySop = sopMapper.selectByPrimaryKey(sopId);
                        String sopName = "";
                        String sopType = "";
                        if(null != querySop){
                            sopName = querySop.getTitle();
                            sopType = querySop.getSopType();
                        }
                        String id = snowFlakeUtil.nextId();
                        pushReqDto.setId(id);
                        pushReqDto.setPushUser(userId);
                        pushReqDto.setPushUserName(userName);
                        pushReqDto.setSopName(sopName);
                        pushReqDto.setSopType(sopType);
                        sopManageMapper.insertPushRecord(pushReqDto);
                        // 插入到盘古
                        if(!sopIds.contains(sopId)){
                            JSONObject sop = new JSONObject();
                            sop.put("push_type",sopType);
                            sop.put("push_title", sopName);
                            sop.put("push_sopid", sopId);
                            sops.add(sop);
                            sopIds.add(sopId);
                        }
                        clueGuids.add(receiveUser);
                        Integer successCount = 0;
                        if(successMap.containsKey(receiveUser)){
                            successCount = successMap.get(receiveUser);
                        }
                        successCount++;
                        successMap.put(receiveUser, successCount);

                    }
                }else {
                    Integer failCount = 0;
                    if(failMap.containsKey(receiveUser)){
                        failCount = failMap.get(receiveUser);
                    }
                    failCount++;
                    failMap.put(receiveUser, failCount);
                }
            } catch (Exception e) {
                log.error("推送失败：{}", e);
                Integer failCount = 0;
                if(failMap.containsKey(receiveUser)){
                    failCount = failMap.get(receiveUser);
                }
                failCount++;
                failMap.put(receiveUser, failCount);

            }
        }
        if(successMap.size() > 0){
            // 插入盘古后台
            json.put("Sops", sops);
            json.put("ClueGuids", clueGuids.toArray());
            addPushRecordToPangu(json, authorization);
        }
        successResDto.setFail(failMap.size());
        successResDto.setSuccess(successMap.size());
        return successResDto;
    }

    public List<String> getAllRole(){
        LoginUserResDto loginUserResDto = this.getCurrentUser();
        if (null == loginUserResDto) {
            throw new BusinessException(ResultStatus.NO_LOGIN.getErrorMsg(), ResultStatus.FAILOfficial);
        }
        List<String> getAllRole = new ArrayList<>();
        String mainRole = loginUserResDto.getMainRole();
        String minorRole = loginUserResDto.getMinorRole();
        if(StringUtils.hasText(mainRole)){
            getAllRole.add(mainRole);
        }
        if(StringUtils.hasText(minorRole)){
            String[] minorRoles = minorRole.split(",");
            for(String role : minorRoles){
                getAllRole.add(role);
            }
        }
        return getAllRole;
    }

    private String addPushRecordToPangu(JSONObject json, String authorization){
        log.info("开始推送sop记录，url：{},参数：{}", addClueSopRecordUrl, json.toJSONString());
        Map param = new HashMap();
        param.put("Authorization", authorization);
        String result = HttpClientUtil.doPostHttps(addClueSopRecordUrl, json.toJSONString(), param, 5000);
        log.info("推送sop记录结束，result：{}", result);
        if(StringUtils.hasText(result)){
            JSONObject resultJson = JSONObject.parseObject(result);
            if(resultJson.containsKey("status") && resultJson.getInteger("status") == ResultStatus.SUCCESS.getErrorCode()){
                return resultJson.getString("result");
            }
        }
        return "";
    }
}